import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import express from "express";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";

const sessionTransport: Map<string, SSEServerTransport> = new Map();

const createServer = () => {
  const server = new McpServer({
    name: "hello-mcp-server",
    version: "1.0.0",
  });
  
  server.tool(
    "hello_mcp",
    "a simple tool return hello mcp",
    {
    },
    async () => {
      console.log("Hello mcp");
      return {
        content: [{
          type: "text",
          text: 'hello mcp',
        }]
      }
    },
  );
  return server;
}

const app = express();

app.get("/sse", async (req, res) => {
  const server = createServer();
  server.server.onclose = async () => {
    await server.close();
    sessionTransport.delete(transport.sessionId);
  };
  const transport = new SSEServerTransport("/messages", res);
  sessionTransport.set(transport.sessionId, transport);
  await server.server.connect(transport);
  return;
});

app.post("/messages", async (req, res) => {
  const sessionId = req.query.sessionId as string;
  if (!sessionId) {
      throw new Error("sessionId can not be null or empty");
  }
  const transport = sessionTransport.get(sessionId);
  if (transport) {
    await transport.handlePostMessage(req, res);
  }
  return;
});

app.listen(3000, () => {
  console.log('MCP Server running on port 3000');
});